<!--
 * @Description: 装卸关系网
 * @Author: xuzp4
 * @Date: 2021-06-11 16:19:36
 * @LastEditors: xuzp4
 * @LastEditTime: 2021-06-29 10:15:06
 * @FilePath: \vue_demo\src\view\load\index.vue
-->

<template>
  <div class="parent">
    <div id="map"></div>
    <div
      class="device-hover"
      v-show="isHoverVisible"
      :style="{ left: hoverLeft + 'px', top: hoverTop + 'px' }"
    >
      {{ name }}
    </div>
    <div
      ref="modifyDevice"
      class="modify-device"
      v-show="isModifyVisible"
      :style="{ left: left + 'px', top: top + 'px' }"
      @click.stop
    >
      <el-button @click="handleSubmit">修改设备目的地</el-button>
      <el-select v-model="value" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </div>
  </div>
</template>

<script>
import { excavatorData, minecardData1, minecardData2 } from "./data.js";
import { getLine, sympleLine } from "./data/data";
// import minecardImg from "../../assets/切图/img_Minecart.svg";
// import excavatorImg from "../../assets/my.png";
// import road from "../../assets/img/road.png";
const mapboxgl = require("mapbox-gl");
export default {
  data() {
    return {
      value: "",
      left: 0,
      top: 0,
      hoverLeft: 0,
      hoverTop: 0,
      isModifyVisible: false,
      isHoverVisible: false,
      name: "",
      options: [
        { label: "平台567", value: "567" },
        { label: "平台568", value: "568" },
        { label: "平台569", value: "569" },
      ],
      moveSpeed: 100, // 步数，两点中间插入的点数量
      isMove: false, // 动画开启
      times: 0, // 当前车子行驶的步数
      timeInterval: 10000 // 获取数据周期
    };
  },
  mounted() {
    this.currentMinecard = minecardData1;
    // 加载挖机点，线段（id,起始点，结束点，经纬度），根据挖机的百分比，线段id，显示挖机的位置，
    // 挖机点击事件，线段点击事件
    this.initMap();
    this.queryMinecard();
  },
  watch: {
    isModifyVisible(newVal, oldVal) {
      if (newVal) {
        document.body.addEventListener("click", this.toggleModifyVisible);
      } else {
        document.body.removeEventListener("click", this.toggleModifyVisible);
      }
    },
  },
  methods: {
    initMap() {
      let map;
      mapboxgl.accessToken =
        "pk.eyJ1IjoieHUwNDMwIiwiYSI6ImNrcHMzeGNhbDAzcHoyb280cmM1MGEzYXYifQ.uZFE2jGWs46691vFMwQLPA";
      this.map = map = new mapboxgl.Map({
        container: "map",
        // style: "mapbox://styles/mapbox/satellite-v9",
        style: "mapbox://styles/xu0430/ckqg0r0ng1kk217o6h54ontd1/draft",
        // style: "mapbox://styles/xu0430/ckps5kgtp3m1118ps33f0yohy",
        // style: "mapbox://styles/xu0430/ckps5kgtp3m1118ps33f0yohy/draft",
        zoom: 14,
        minZoom: 13,
        maxZoom: 19,
        center: [113.722, 24.552],
        doubleClickZoom: false,
        dragRotate: false,
        // pitch: 40,
        // maxPitch: 50,
      });
      this.popup = new mapboxgl.Popup({
        closeButton: false,
        closeOnClick: false,
      });
      this.initData(map);
    },
    initData(map) {
      map.on("load", () => {
        // this.addImg(map)
        this.darwLine(map);
        this.handleLineClick(map);
        this.drawExcavator(map);
        this.handleExcavatorClick(map);
        this.handleExcavatorMouseenter(map);
        this.handleMapZoom(map);
        this.drawMineCard(map);
        this.animateDevice(map);
        this.handleMineCardClick(map)
      });
    },
    addImg(map) {
        // map.loadImage(minecardImg, (error, image) => {
        //   if (error) {
        //     throw new Error(error);
        //   }
        //   map.addImage("minecard", image);
        // });
        // map.loadImage(excavatorImg, (error, image) => {
        //   if (error) {
        //     throw new Error(error);
        //   }
        //   map.addImage("excavator", image);
        // });
        //   map.loadImage(road, (error, image) => {
        //   if (error) {
        //     throw new Error(error);
        //   }
        //   map.addImage("road", image);
        // });
    },
    drawExcavator(map) {
      const source = [];
      excavatorData.forEach((point) => {
        source.push({
          type: "Feature",
          geometry: {
            type: "Point",
            coordinates: [point.longitude, point.latitude],
          },
          properties: {
            image: "excavator",
            info: point,
            name:point.name
          },
        });
      });
      map.addSource("excavator", {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: source,
        },
      });
      map.addLayer({
        id: "excavator",
        source: "excavator",
        type: "symbol",
        layout: {
          "icon-image": ["get", "image"],
          "icon-allow-overlap": true,
          "icon-size": 0.8,
          "text-allow-overlap": true,
          'text-field': ['get', 'name'],
					'text-anchor': 'bottom',
					'text-offset': [0.8, -0.5],
					'icon-offset': [-5, -13],
          'text-size':20,
          "text-font": ["Open Sans Bold", "Arial Unicode MS Bold"],
        },
        paint:{
         "text-color": "#202",
          "text-halo-color": "#fff",
          "text-halo-width": 2
        }
      });
    },
    handleExcavatorMouseenter(map) {
      map.on("mouseenter", "excavator", (e) => {
        map.getCanvas().style.cursor = "pointer";
        var description = JSON.parse(e.features[0].properties.info).name;
        const point = map.project(e.features[0].geometry.coordinates);
        this.hoverLeft = point.x;
        this.hoverTop = point.y - 50;
        this.isHoverVisible = true;
        this.name = description;
      });
      map.on("mouseleave", "excavator", (e) => {
        map.getCanvas().style.cursor = "";
        this.isHoverVisible = false;
      });
    },
    handleExcavatorClick(map) {
      map.on("click", "excavator", (e) => {
        e.originalEvent.stopPropagation();
        const point = map.project(e.features[0].geometry.coordinates);
        this.left = point.x;
        this.top = point.y;
        this.isModifyVisible = true;
      });
    },
    darwLine(map) {
      let lineSource = sympleLine;
      map.addSource("line", {
        type: "geojson",
        data: lineSource,
      });
      map.addLayer({
        id: "line-animation",
        type: "line",
        source: "line",
        layout: {
          "line-cap": "round",
          "line-join": "round",
        },
        paint: {
          "line-color": "red",
          "line-opacity": 1,
          // "line-width": 5, 
          // "line-blur": 5
          "line-pattern":'road'
          // "line-pattern":'roadOut'
          // "line-pattern":['get','style']
        },
      });
    },
    handleLineClick(map) {
      map.on("click", "line-animation", (e) => {
        alert(`点击line${e.features[0].properties.id}`);
      });
    },
    handleMapZoom(map) {
      map.on("zoomend", (e) => {
        const curZoom = e.target.getZoom();
        map.setLayoutProperty(
          "excavator",
          "icon-size",
          0.8 + 0.05 * (curZoom - 13)
        );
        map.setPaintProperty(
          "line-animation",
          "line-width",
          5+ 2 * (curZoom - 13)
        );
      });
    },
    toggleModifyVisible() {
      this.isModifyVisible = !this.isModifyVisible;
    },
    handleSubmit() {
      this.$notify({
        title: "成功",
        message: "切换平台成功",
        type: "success",
        duration: 2000,
      });
      this.toggleModifyVisible();
    },

    drawMineCard(map) {
      // 绘制宽体车
      const source = [];
      minecardData1.forEach((point) => {
        source.push({
          type: "Feature",
          geometry: {
            type: "Point",
            coordinates: [point.longitude, point.latitude],
          },
          properties: {
            image: "minecard",
            info: point,
          },
        });
      });
      map.addSource("minecard", {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: source,
        },
      });
      map.addLayer({
        id: "minecard",
        source: "minecard",
        type: "symbol",
        layout: {
          "icon-image": ["get", "image"],
          "icon-allow-overlap": true,
          "icon-size": 0.8,
          "text-allow-overlap": true,
          	'text-field': ['get', 'name'],
					'text-anchor': 'top',
					'text-offset': [0, 0.5]
        },
      });
    },
    queryMinecard() {
      let i = 0;
      setInterval(() => {
        i++;
        const newData = i % 2 ? minecardData2 : minecardData1;
        this.movePoints = this.computeDistance(newData, this.currentMinecard);
        this.minecardIds = newData.map((item) => item.id);
        // console.log("movePoints", this.movePoints);
        this.currentMinecard = newData;
      }, this.timeInterval);
    },
    // 计算两次响应之间每个点的距离
    computeDistance(newLorrys, oldLorrys) {
      let movePoints = [];
      newLorrys.map((newLorry) => {
        oldLorrys.map((oldLorry) => {
          if (newLorry.id === oldLorry.id) {
            const distanceX = newLorry.longitude - oldLorry.longitude;
            const distanceY = newLorry.latitude - oldLorry.latitude;
            const tempDis = {
              id: newLorry.id,
              info: newLorry,
              x: distanceX / this.moveSpeed,
              y: distanceY / this.moveSpeed,
              startX: Number(oldLorry.longitude),
              startY: Number(oldLorry.latitude),
              endX: Number(newLorry.longitude),
              endY: Number(newLorry.latitude),
            };
            movePoints.push(tempDis);
          }
        });
      });
      this.isMove = true; // 开启动画
      this.times = 0;
      return movePoints;
    },
    // 实时移动
    animateDevice(map) {
      // this.movePoints
      const getPoints = () => {
        const points = this.minecardIds.map((id) => {
          let point = {};
          this.movePoints.forEach((item, i) => {
            if (id === item.id) {
              let disX = item.startX;
              let disY = item.startY;
              if (this.times <= this.moveSpeed) {
                disX = item.startX + item.x * this.times;
                disY = item.startY + item.y * this.times;
              }
              point = {
                type: "Feature",
                geometry: {
                  type: "Point",
                  coordinates: [disX, disY],
                },
                properties: {
                  image: "minecard",
                  info: item.info,
                },
              };
            }
          });
          return point;
        });
        return points;
      };
      setInterval(() => {
        if (this.isMove) {
          this.times++;
          if (this.times <= this.moveSpeed) {
            const points = getPoints()
            // console.log("data", points);
            map.getSource("minecard").setData({type: "FeatureCollection",features:points});
          }
        }
      }, this.timeInterval / this.moveSpeed);
    },

    // 1. 绘制所有宽体车的位置
    // 2. 等10秒后查询宽体车的位置，计算每个点的距离，中间插入点，在10秒内走完路程
    handleMineCardClick(map) {
      map.on('click','minecard',e => {
          e.originalEvent.stopPropagation();
        console.log('点击宽体车',e.features[0])
        const point = map.project(e.features[0].geometry.coordinates);
        this.left = point.x;
        this.top = point.y;
        this.isModifyVisible = true;
      })
    }
  },
};
</script>

<style>
.parent {
  width: 100%;
  height: 100%;
  color: #fff;
}
#map {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}
.modify-device {
  position: absolute;
}
.device-hover {
  position: absolute;
}
</style>
